package pers.qianyu.month_202012.date_20201211;

import org.junit.*;

import java.util.*;

/**
 * 90. 子集 II
 * https://leetcode-cn.com/problems/subsets-ii/
 *
 * @author mizzle rain
 * @date 2020年12月11日22:14:31
 */
public class SubsetsWithDup2 {
    List<List<Integer>> res = new ArrayList<>();

    /**
     * 回溯解法
     */
    public List<List<Integer>> subsetsWithDup(int[] nums) {
        Arrays.sort(nums);
        ArrayList<Integer> path = new ArrayList<>();
        backTracking(path, nums, 0);
        return res;
    }

    private void backTracking(ArrayList<Integer> path, int[] nums, int startIndex) {
        res.add(new ArrayList<>(path));
        for (int i = startIndex; i < nums.length; i++) {
            // 剪掉重复头结点的树
            if (i != startIndex && nums[i - 1] == nums[i]) {
                continue;
            }
            path.add(nums[i]);
            backTracking(path, nums, i + 1);
            path.remove(path.size() - 1);
        }
    }

    @Test
    public void test1() {
        List<List<Integer>> result = new SubsetsWithDup2()
                .subsetsWithDup(new int[]{1, 2, 2});
        result.forEach(System.out::println);
    }
}
